﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.Core.DBUtility;
using Microhard.Core;
using Microhard.Plat.CRM.Customers.Interface;
using Microhard.Plat.CRM.Customers.DataAccess;
using Microhard.Plat.CRM.Customers.DTO;
using Microhard.Plat.CRM.Customers.Msg;
using Microhard.Plat.CRM.Customers.Models;


namespace Microhard.Plat.CRM.Customers.Impl
{
    public class SaleLeadImpl : ISaleLead
    {
        public Microhard.Core.DBUtility.ExecutedResult Add(Models.SaleLeadModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            Microhard_Plat_CustomersEntities db = new Microhard_Plat_CustomersEntities();
            //生成客户
            var existCustomer = db.Customers.SingleOrDefault(s => s.CustomerID == model.CustomerID);
            if (existCustomer == null)
            {
                existCustomer = model.Customer.ToEntity();
                existCustomer.CreateTime = DateTime.Now;
                existCustomer.CompanyID = this.scope.EmpInfo.CompanyID;
                existCustomer.SaleEmployeeID = this.scope.EmpInfo.EmployeeID;
                existCustomer.CustomerID = Guid.NewGuid();
                db.Customers.AddObject(existCustomer);

            }
            else
            {
                //更新用户信息
                existCustomer.Name = model.Customer.Name;
                existCustomer.Cellphone = model.Customer.Cellphone;
                existCustomer.Address = model.Customer.Address;
            }

            if (existCustomer.SaleLeads.Count == 0)
            {
                //生成销售线索
                var op = model.ToEntity();
                op.CreateTime = DateTime.Now;
                op.CustomerID = existCustomer.CustomerID;
                op.Status = true;
                existCustomer.SaleLeads.Add(op);
            }
            else
            {
                var only = existCustomer.SaleLeads.First();
                only.Description = model.Description;
                only.CreateTime = DateTime.Now;
                only.GetPrdInfoResource = model.GetPrdInfoResource;
                only.LeadSourceType = model.LeadSourceType;
                only.ReqTimeLine = model.ReqTimeLine;
            }

            try
            {
                db.SaveChanges();
            }
            catch (System.Exception ex)
            {
                rtn.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, SaleLeadMsg.AddFailed);
                Log.Error("ISaleLead.Add", ex);
            }
            return rtn;
        }

        public Microhard.Core.DBUtility.ExecutedResult Update(Models.SaleLeadModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            Microhard_Plat_CustomersEntities db = new Microhard_Plat_CustomersEntities();
            //修改线索信息
            var sl = db.SaleLeads.SingleOrDefault(s => s.SaleLeadID == model.SaleLeadID);
            sl.Description = model.Description;
            sl.Status = model.Status;
            sl.GetPrdInfoResource = model.GetPrdInfoResource;
            sl.ReqTimeLine = model.ReqTimeLine;
            sl.LeadSourceType = model.LeadSourceType;
            sl.OldCustomerID = model.OldCustomerID;

            //修改客户信息
            var customer = db.Customers.SingleOrDefault(s => s.CustomerID == sl.CustomerID);
            customer.Address = model.Customer.Address;
            customer.Cellphone = model.Customer.Cellphone;
            customer.City = model.Customer.City;
            customer.Province = model.Customer.Province;
            customer.Name = model.Customer.Name;
            try
            {
                db.SaveChanges();
            }
            catch (System.Exception ex)
            {
                rtn.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, SaleLeadMsg.AddFailed);
                Log.Error("ISaleLead.Add", ex);
            }
            return rtn;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            Microhard_Plat_CustomersEntities db = new Microhard_Plat_CustomersEntities();

            var toDelete = db.SaleLeads.Where(e => ids.Contains(e.SaleLeadID)).ToList();
            toDelete.ForEach(e =>
            {
                db.SaleLeads.DeleteObject(e);
            });
            if (result.ErrorMsg.Count == 0)
            {
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, SaleLeadMsg.DeleteFailed);
                    Log.Error("IEmployee.Delete", ex);
                }
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(Models.SaleLeadModel model)
        {
            throw new NotImplementedException();
        }

        public Models.SaleLeadModel GetModelByID(Guid id)
        {
            Microhard_Plat_CustomersEntities db = new Microhard_Plat_CustomersEntities();
            return db.SaleLeads.SingleOrDefault(c => c.SaleLeadID == id).ToModel();
        }

        public Models.SaleLeadModel GetModelByModel(Models.SaleLeadModel model)
        {
            throw new NotImplementedException();
        }

        public List<Models.SaleLeadModel> Query(Models.SaleLeadModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            totalCount = 0;
            Microhard_Plat_CustomersEntities db = new Microhard_Plat_CustomersEntities();
            IEnumerable<SaleLead> entities = from b in db.SaleLeads
                                             where b.Customer.SaleEmployeeID == this.scope.EmpInfo.EmployeeID
                                             && b.Customer.CompanyID == this.scope.EmpInfo.CompanyID
                                             select b;
            if (entities != null)
            {
                totalCount = entities.Count();
                var pagedEntities = entities.OrderBy(p => p.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                if (pagedEntities != null && pagedEntities.Count > 0)
                    return pagedEntities.Select(m => m.ToModel()).ToList();
            }
            return new List<SaleLeadModel>();
        }

        public List<Models.SaleLeadModel> Query(Models.SaleLeadModel Model)
        {
            throw new NotImplementedException();
        }

        public Microhard.Core.DBUtility.ScopeResult scope
        {
            set;
            get;
        }
    }
}
